const express = require('express');
const router = express.Router();
const sqlFn = require('../mysql');
// jwt
const jwt = require('jsonwebtoken');
// 导入密钥
const config = require('../secert');
// 导入商品列表信息
const goodsList = require('../goods');
// 导入城市信息
const cityInfo = require('../city');

// 测试接口
router.get('/', (req, res) => {
    res.send('服务器启动成功')
})

/** ------------------------------------ 登录注册接口 ----------------------------------------------- */
/**
 * 登陆接口
 */
// 已注册直接登录，未注册直接注册
router.post("/login", (req, res) => {
    const { phone, password } = req.body;
    const sql = "select * from user where `phone`=?";
    const arr = [phone, password];
    sqlFn(sql, phone, result => {
        if (result.length > 0) {  // 已经注册了
            const sqlPwd = "select * from user where `phone`=? and `password`=?";
            sqlFn(sqlPwd, arr, res2 => {
                if (res2.length > 0) {
                    const token = jwt.sign({
                        id: result[0].id,
                        phone: result[0].phone
                    }, config.jwtSecret, {
                        expiresIn: 60 * 1
                    })
                    res.send({
                        status: 200,
                        data: token,
                        msg: '登录成功'
                    });
                } else {
                    res.send({
                        status: 404,
                        msg: '密码错误'
                    })
                }
            })
        } else {  // 未注册
            const sqlReg = "insert into user values (null,'一个新用户呀',?,?,'','','','男')";
            const arr2 = [password, phone];
            sqlFn(sqlReg, arr2, result => {
                if (result.affectedRows > 0) {
                    res.send({
                        msg: "注册成功",
                        status: 200
                    })
                } else {
                    res.status(401).json({
                        errors: "注册失败"
                    })
                }
            })
        }
    })
})

/**
 * 获取用户信息
 */
router.get("/getuserInfo", (req, res) => {
    const id = req.query.id;
    const sql = "select * from user where `id`=?";
    sqlFn(sql, id, result => {
        if (result.length > 0) {
            res.send({
                status: 200,
                data: result[0]
            })
        } else {
            res.send({
                status: 500,
                msg: "暂无数据"
            })
        }
    })
})

/**
 * 修改用户信息
 */
router.get("/update/userInfo", (req, res) => {
    var id = req.query.id;
    var username = req.query.username || "";
    var password = req.query.password || "";
    var phone = req.query.phone || "";
    var gender = req.query.gender || "";
    var sql = "update user set username=?,phone=?,password=?,gender=? where id=?";
    var arr = [username, phone, password, gender, id];
    sqlFn(sql, arr, result => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "修改成功"
            })
        } else {
            res.send({
                status: 500,
                msg: "修改失败"
            })
        }
    })
})

/** ------------------------------------ 商品信息接口 ----------------------------------------------- */

/**
 * 获取用户信息
 */
router.get("/goodsList", (req, res) => {
    res.send({
        status: 200,
        data: goodsList
    })
})

/** ------------------------------------ 收货地址接口 ----------------------------------------------- */

router.get("/getuserInfo/address", (req, res) => {
    const id = req.query.id;
    const sql = "select `address` from user where `id`=?";
    sqlFn(sql, id, result => {
        if (result.length > 0) {
            res.send({
                status: 200,
                data: result[0]
            })
        } else {
            res.send({
                status: 500,
                msg: "暂无数据"
            })
        }
    })
})

router.get("/getuserInfo/address/add", (req, res) => {
    const id = req.query.id;
    const address = req.query.address;
    let arr = [address, id];
    const sql = "update user set `address`=? where id=?";
    sqlFn(sql, arr, result => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "修改成功"
            })
        } else {
            res.send({
                status: 500,
                msg: "修改失败"
            })
        }
    })
})

/** ------------------------------------ 城市信息接口 ----------------------------------------------- */

router.get("/cityInfo", (req, res) => {
    res.send({
        status: 200,
        data: cityInfo
    })
})

/** ------------------------------------ 购物车接口 ----------------------------------------------- */

/**
 * 添加购物车（跳到详情页去添加）
 */
router.get("/shopCart/add", (req, res) => {
    let user_id = req.query.user_id;
    let goods_name = req.query.goods_name;
    let goods_num = req.query.goods_num;
    let goods_price = req.query.goods_price;
    let goods_choose = req.query.goods_choose;
    let goods_img = req.query.goods_img;

    let sql = "select * from `shopCart` where `user_id`=? and `goods_name`=?";
    let arr = [user_id, goods_name];
    sqlFn(sql, arr, result => {
        // 有数据
        if (result.length > 0) {
            if (result[0].goods_choose !== goods_choose) {
                // 正常插入数据
                let arr2 = [user_id, goods_name, goods_num, goods_price, goods_choose, goods_img];
                let sql2 = "insert into shopCart values (null,?,?,?,?,?,?)";
                sqlFn(sql2, arr2, result => {
                    if (result.affectedRows > 0) {
                        res.send({
                            status: 200,
                            msg: "购物车添加成功"
                        })
                    } else {
                        res.send({
                            status: 500,
                            msg: "购物车添加失败"
                        })
                    }
                })
            } else {
                // 更新数据
                goods_num = `${Number(req.query.goods_num) + Number(result[0].goods_num)}`;
                let sql2 = "update shopCart set `goods_num`=? where `user_id`=? and `goods_name`=?";
                let arr2 = [goods_num, user_id, goods_name];
                sqlFn(sql2, arr2, result => {
                    if (result.affectedRows > 0) {
                        res.send({
                            status: 200,
                            msg: "购物车添加成功"
                        })
                    } else {
                        res.send({
                            status: 500,
                            msg: "购物车添加失败"
                        })
                    }
                })
            }
        } else {
            // 没有数据
            let arrno = [user_id, goods_name, goods_num, goods_price, goods_choose, goods_img];
            let sqlno = "insert into shopCart values (null,?,?,?,?,?,?)";
            sqlFn(sqlno, arrno, result => {
                if (result.affectedRows > 0) {
                    res.send({
                        status: 200,
                        msg: "购物车添加成功"
                    })
                } else {
                    res.send({
                        status: 500,
                        msg: "购物车添加失败"
                    })
                }
            })
        }
    })
})

/**
 * 在商品列表获取购物车信息
 */
router.get("/getShopCart", (req, res) => {
    const user_id = req.query.user_id;
    const sql = "select * from `shopCart` where `user_id`=?";
    sqlFn(sql, user_id, result => {
        if (result.length > 0) {
            res.send({
                status: 200,
                data: result
            })
        } else {
            res.send({
                status: 500,
                msg: "暂无数据"
            })
        }
    })
})

/**
 * 在商品列表页当商品数量为1时，点击“-”号对商品数据进行删除
 */
router.get('/shopCart/del', (req, res) => {
    let id = req.query.id;
    let sql = "delete from `shopCart` where `id`=?";
    sqlFn(sql, id, result => {
        if (result.affectedRows === 1) {
            res.send({
                status: 200,
                msg: '删除成功'
            })
        } else {
            res.send({
                status: 500,
                msg: '删除失败'
            })
        }
    })
})

/**
 * 一键删除所有购物车商品
 */
router.get('/shopCart/delAll', (req, res) => {
    let user_id = req.query.user_id;
    let sql = "delete from `shopCart` where `user_id`=?";
    sqlFn(sql, user_id, result => {
        if (result.affectedRows === 1) {
            res.send({
                status: 200,
                msg: '全部商品删除成功'
            })
        } else {
            res.send({
                status: 500,
                msg: '全部商品删除失败'
            })
        }
    })
})

/** ------------------------------------ 订单接口 ----------------------------------------------- */

/**
 * 在商品列表提交订单信息
 */
router.get('/addOrder', (req, res) => {
    let user_id = req.query.user_id;
    let goods_info = req.query.goods_info;
    let total = req.query.total;
    // 生成订单号
    function setTimeDateFmt(s) {  // 个位数补齐十位数
        return s < 10 ? '0' + s : s;
    }
    function createordernum() {
        const now = new Date()
        let month = now.getMonth() + 1
        let day = now.getDate()
        let hour = now.getHours()
        let minutes = now.getMinutes()
        let seconds = now.getSeconds()
        month = setTimeDateFmt(month)
        day = setTimeDateFmt(day)
        hour = setTimeDateFmt(hour)
        minutes = setTimeDateFmt(minutes)
        seconds = setTimeDateFmt(seconds)
        let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
        return orderCode;
        //基于年月日时分秒+随机数生成订单编号
    }    
    let order_code = createordernum();
    let sql = "insert into `order` values (null,?,?,?,?,1)"
    let arr = [user_id, goods_info, total, order_code];
    sqlFn(sql, arr, result => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "订单提交成功"
            })
        } else {
            res.send({
                status: 500,
                msg: "订单提交失败"
            })
        }
    })
})

/**
 * 获取当前订单信息
 */
router.get('/getOrder', (req, res) => {
    let user_id = req.query.user_id;
    let sql = "select * from `order` where `user_id`=?"
    sqlFn(sql, user_id, result => {
        if (result.length > 0) {
            res.send({
                status: 200,
                data: result[result.length-1]
            })
        } else {
            res.send({
                status: 500,
                msg: "暂无数据"
            })
        }
    })
})

/**
 * 获取所有订单信息
 */
 router.get('/getAllOrder', (req, res) => {
    let user_id = req.query.user_id;
    let sql = "select * from `order` where `user_id`=? order by `id` desc"
    sqlFn(sql, user_id, result => {
        if (result.length > 0) {
            res.send({
                status: 200,
                data: result
            })
        } else {
            res.send({
                status: 500,
                msg: "暂无数据"
            })
        }
    })
})

/**
 * 删除订单信息
 */
 router.get('/delOrder', (req, res) => {
    let id = req.query.id;
    let sql = "delete from `order` where `id`=?";
    sqlFn(sql, id, result => {
        if (result.affectedRows === 1) {
            res.send({
                status: 200,
                msg: '订单删除成功'
            })
        } else {
            res.send({
                status: 500,
                msg: '订单删除失败'
            })
        }
    })
})

/** ------------------------------------ 对接支付宝沙箱接口 ----------------------------------------------- */
// 引入支付宝配置信息
const alipaySdk = require('../zfb/zfb_config')
const AlipayFromData = require('alipay-sdk/lib/form').default;

router.post('/pay', (req, res) => {
    // 前端给后端的数据（订单号，金额，商品描述等信息）
    let orderId = req.body.orderId;
    let orderMoney = req.body.orderMoney;
    let orderTitle = req.body.orderTitle;
    let orderInfo = req.body.orderInfo;
    // 对接支付宝
    const formData = new AlipayFromData()
    formData.setMethod('get')

    formData.addField('returnUrl', 'http://localhost:8080/#/paysuccess'); // 付款成功打开的链接
    formData.addField('bizContent', {
        // 传递的订单号
        outTradeNo: orderId,
        // productCode
        product_code: 'FAST_INSTANT_TRADE_PAY',
        // 金额
        total_amount: orderMoney,
        // 商品标题
        subject: orderTitle,
        // 商品描述
        body: orderInfo,
    });

    const result = alipaySdk.exec(
        'alipay.trade.page.pay',
        {},
        { formData: formData },
    );

    result.then((resp) => {
        res.send({
            success: '支付成功',
            code: 200,
            result: resp
        });
    });
})

// 引入网络请求（向支付宝发请求）
const axios = require('axios')
router.post('/pay/orderStatu', (req, res) => {
    let out_trade_no = req.body.out_trade_no;
    let trade_no = req.body.trade_no;

    // 对接支付宝
    const formData = new AlipayFromData()
    formData.setMethod('get')
    formData.addField('bizContent', {
        out_trade_no,
        trade_no
    });

    const result = alipaySdk.exec(
        'alipay.trade.query',
        {},
        { formData: formData },
    );

    result.then((resData) => {
        axios({
            url: resData,
            method: 'get'
        }).then(data => {
            // console.log(data);
            let r = data.data.alipay_trade_query_response;
            if (r.code === '10000') {
                switch (r.trade_status) {
                    case 'WAIT_BUYER_PAY':
                        res.send({
                            success: true,
                            code: 200,
                            msg: '支付宝有交易记录，没付款'
                        })
                        break;
                    case 'TRADE_FINISHED': // 交易完成，不能退款
                        res.send({
                            success: true,
                            code: 200,
                            msg: '订单已完成'
                        })
                        break;
                    case 'TRADE_SUCCESS': // 刚交易完成，可以退款
                        res.send({
                            success: true,
                            code: 200,
                            msg: '订单已完成'
                        })
                        break;
                    case 'TRADE_CLOSED':
                        res.send({
                            success: true,
                            code: 200,
                            msg: '交易关闭，没有支付成功'
                        })
                        break;
                }
            } else if (r.code === '40004') {
                res.json('交易不存在')
            }
        }).catch(err => {
            res.json({
                msg: '查询失败',
                err
            })
        })
    });
})

module.exports = router;